package com.object.module.sys.service.impl;

import com.object.configuration.utils.Q;
import com.object.module.sys.entity.ChatMesagger;
import com.object.module.sys.entity.TUserEntity;
import com.object.module.sys.service.ChatStorageSerivce;
import com.object.module.sys.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatStorageSerivceimpl implements ChatStorageSerivce {

    @Value("${redis.survival.time}")
    private Integer time;

    @Autowired
    private TUserService tUserService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 查询 redis的 聊天记录
     * @param userId
     * @param chatUserId
     * @return
     */
    @Override
    public Q findChatStrorage(Integer userId, Integer chatUserId) {
         String key=userId>chatUserId?chatUserId+"_id_"+userId:userId+"_id_"+chatUserId;
        List<ChatMesagger> list = (List<ChatMesagger>) redisTemplate.opsForValue().get(key);
        list.forEach(chat->{
             chat.setUser(tUserService.getById(userId));
              chat.setChatuser(tUserService.getById(chatUserId));
        });
        return Q.ok().put("data",list);
    }

    /**
     * 保存 聊天记录
     * @param chatMesagger
     * @return
     */
    @Override
    public Q save(ChatMesagger chatMesagger) {
        Integer userId = chatMesagger.getUserId();
        Integer charuserId = chatMesagger.getCharuserId();
        String key=userId>charuserId?charuserId+"_id_"+userId:userId+"_id_"+charuserId;
        List<ChatMesagger> list = (List<ChatMesagger>) redisTemplate.opsForValue().get(key);
        list.add(chatMesagger);
        redisTemplate.opsForValue().set(key,list,time, TimeUnit.DAYS);
        return Q.ok();
    }


}
